package ldkxingzhe.ldkxingzhedemo.net;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import ldkxingzhe.ldkxingzhedemo.R;
import ldkxingzhe.ldkxingzhedemo.utils.LogDemo;


/**
 * Created by xingzhe on 15/10/16.
 */
public class VolleyDemoActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = VolleyDemoActivity.class.getSimpleName();

    RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buttons);
        ((TextView)findViewById(R.id.title)).setText("Volley测试");
        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(this);
        requestQueue = Volley.newRequestQueue(this);
    }

    @Override
    public void onClick(View v) {
/*        StringRequest request = new StringRequest("http://www.baidu.com",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        LogDemo.v(TAG,"response is " + response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        LogDemo.v(TAG,"error happened.");
                    }
                }
        );*/

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", "ldkxingzhe");
            jsonObject.put("password", "123456");
        } catch (JSONException e) {
            e.printStackTrace();
        }


        JsonObjectRequest request = new JsonObjectRequest("http://httpbin.org/post",jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        LogDemo.v(TAG,"json response is " + response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        LogDemo.v(TAG,"error, happened");
                        LogDemo.v(TAG,"error is " + error);
                    }
                }
        );
        LogDemo.v(TAG,"now add a Request");
        requestQueue.add(request);
    }
}
